//
//  AppDelegate.m
//  DrinkingPlan
//
//  Created by 张德广 on 2019/3/15.
//  Copyright © 2019 Drinking Plan. All rights reserved.
//

#import "AppDelegate.h"
#import "DPPlanViewController.h"
#import "DPMainViewController.h"
#import "JPUSHService.h"
// iOS10 注册 APNs 所需头文件
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#import <UserNotifications/UserNotifications.h>
#endif
#import "DPModel.h"
#import "DPSingleTon.h"


@interface AppDelegate () <UNUserNotificationCenterDelegate>

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    //notice: 3.0.0 及以后版本注册可以这样写，也可以继续用之前的注册方式
    JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
    if (@available(iOS 12.0, *)) {
        entity.types = JPAuthorizationOptionAlert|JPAuthorizationOptionBadge|JPAuthorizationOptionSound|JPAuthorizationOptionProvidesAppNotificationSettings;
    } else {
        // Fallback on earlier versions
    }
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
        // 可以添加自定义 categories
        // NSSet<UNNotificationCategory *> *categories for iOS10 or later
        // NSSet<UIUserNotificationCategory *> *categories for iOS8 and iOS9
    }
    [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];
    // 如需继续使用 pushConfig.plist 文件声明 appKey 等配置内容，请依旧使用 [JPUSHService setupWithOption:launchOptions] 方式初始化。
    [JPUSHService setupWithOption:launchOptions appKey:@"b6531fe5e49560ca429d5588"
                          channel:@"App Store"
                 apsForProduction:true
            advertisingIdentifier:nil];
    IQKeyboardManager *keyboardManager = [IQKeyboardManager sharedManager];
    keyboardManager.enable = YES; // 控制整个功能是否启用
    
    _window = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
    _window.backgroundColor = [UIColor whiteColor];
    
    DPPlanViewController *planVc = [[DPPlanViewController alloc]init];
    UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:planVc];
    
    _window.rootViewController = nav;
    [_window makeKeyAndVisible];
    
    [self requestAuthor];
    [self firstSaveModel];
    
    // 当App已经完全退出时，获取userInfo参数过程如下：
    NSDictionary *userInfoLocal = (NSDictionary *)[launchOptions objectForKey:UIApplicationLaunchOptionsLocalNotificationKey];
    NSLog(@"------%@",userInfoLocal);
    
    
    return YES;
}

- (void) firstSaveModel{
    
    NSMutableArray *arr = [NSMutableArray array];
    NSArray *tempArr = [DPSingleTon readModelArrayForDocument:DrinkingCautionPath];
    if (tempArr.count != 0) return;
    
    NSArray *timeArr = @[@"06:30:00",@"08:30:00",@"10:00:00",@"11:30:00",@"12:30:00",@"14:00:00",@"15:30:00",@"17:00:00",@"19:30:00",@"22:00:00"];
    NSArray *waterArr = @[@"200",@"200",@"200",@"100",@"200",@"200",@"200",@"300",@"200",@"200"];
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy/MM/dd HH:mm:ss"];
    
    for (int i = 0; i < timeArr.count; i ++) {
        DPModel *model = [DPModel new];
        model.currentTime = [DPSingleTon getCurrentDetailTime];
        model.time = [NSString stringWithFormat:@"%@ %@",[DPSingleTon getCurrentTime],timeArr[i]];
        model.water = waterArr[i];
        model.notice = @"1";
        
        NSDate *date1 = [formatter dateFromString:[DPSingleTon getCurrentDetailTime]];
        NSDate *date2 = [formatter dateFromString:[NSString stringWithFormat:@"%@ %@",[DPSingleTon getCurrentTime],timeArr[i]]];
        NSComparisonResult result = [date1 compare:date2];
        if (result == NSOrderedAscending) {
            model.status = @"0";
        }else {
            model.status = @"2";
        }
        
        [arr addObject:model];
    }
    
    [DPSingleTon saveModelDictionaryInDocument:arr andPath:DrinkingCautionPath];
}

- (void)requestAuthor {
    
    if (@available(iOS 10.0, *)) {
        UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
        [center requestAuthorizationWithOptions:(UNAuthorizationOptionAlert|UNAuthorizationOptionSound|UNAuthorizationOptionBadge)
                              completionHandler:^(BOOL granted, NSError * _Nullable error) {
                                  if (!error) {
                                      NSLog(@"succeeded!");
                                  }
                              }];
        center.delegate = self;
    } else {
        if([[UIDevice currentDevice].systemVersion doubleValue]>=8.0){//8.0以后使用这种方法来注册推送通知
            UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeBadge|UIUserNotificationTypeSound|UIUserNotificationTypeAlert categories:nil];
            [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
        }else{
            [[UIApplication sharedApplication] registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge) categories:nil]];
        }
    }
}

//App处于前台接收通知时
- (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler{
    
    //收到推送的请求
    UNNotificationRequest *request = notification.request;
    //收到推送的内容
    UNNotificationContent *content = request.content;
    //收到用户的基本信息
    NSDictionary *userInfo = content.userInfo;
    //收到推送消息的角标
    NSNumber *badge = content.badge;
    //收到推送消息body
    NSString *body = content.body;
    //推送消息的声音
    UNNotificationSound *sound = content.sound;
    // 推送消息的副标题
    NSString *subtitle = content.subtitle;
    // 推送消息的标题
    NSString *title = content.title;
    
    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        //此处省略一万行需求代码。。。。。。
        NSLog(@"iOS10 收到远程通知:%@",userInfo);
    }else {
        // 判断为本地通知
        [[NSNotificationCenter defaultCenter]postNotificationName:@"ReceiveNotificationPush" object:nil userInfo:userInfo];

//        if (@available(iOS 10.0, *)) {
//            [[NSNotificationCenter defaultCenter]postNotificationName:@"ReceiveNotificationPush" object:nil userInfo:userInfo];
//        }else {
//        }
    }
    
    // 需要执行这个方法，选择是否提醒用户，有Badge、Sound、Alert三种类型可以设置
    completionHandler(UNNotificationPresentationOptionBadge|
                      UNNotificationPresentationOptionSound|
                      UNNotificationPresentationOptionAlert);
}


//App通知的点击事件
- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler{
    
    //收到推送的请求
    UNNotificationRequest *request = response.notification.request;
    //收到推送的内容
    UNNotificationContent *content = request.content;
    //收到用户的基本信息
    NSDictionary *userInfo = content.userInfo;
    
    
    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        NSLog(@"iOS10 收到远程通知:%@",userInfo);
        //此处省略一万行需求代码。。。。。。
    }else {
        // 判断为本地通知
        [[NSNotificationCenter defaultCenter]postNotificationName:@"ReceiveNotificationPush" object:nil userInfo:userInfo];

        if (@available(iOS 10.0, *)) {
        }else {
        }
    }
    completionHandler(); // 系统要求执行这个方法
}

// 本地通知回调函数，当应用程序在前台时调用
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {
    NSLog(@"notification.userInfo = %@",notification.userInfo);
    
//    if (@available(iOS 10.0, *)) {
//    }else {
//        [self jumpToControllerWithLocationNotification:notification];
//    }
}

- (void)jumpToControllerWithLocationNotification:(UILocalNotification *)localNoti {
    // 如果APP在前台,就不用走通知的方法了
    if ([UIApplication sharedApplication].applicationState == UIApplicationStateActive) {
        return;
    }
    // 获取userInfo
    NSDictionary *userInfo = localNoti.userInfo;
    [[NSNotificationCenter defaultCenter]postNotificationName:@"ReceiveNotificationPush" object:nil userInfo:userInfo];
}


- (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    
    /// Required - 注册 DeviceToken
    [JPUSHService registerDeviceToken:deviceToken];
}
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    //Optional
    NSLog(@"did Fail To Register For Remote Notifications With Error: %@", error);
}


#pragma mark- JPUSHRegisterDelegate

// iOS 12 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center openSettingsForNotification:(UNNotification *)notification API_AVAILABLE(ios(10.0)){
    if (@available(iOS 10.0, *)) {
        if (notification && [notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
            //从通知界面直接进入应用
        }else{
            //从通知设置界面进入应用
        }
    } else {
        // Fallback on earlier versions
    }
}

// iOS 10 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler  API_AVAILABLE(ios(10.0)){
    // Required
    NSDictionary * userInfo = notification.request.content.userInfo;
    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
    }
    completionHandler(UNNotificationPresentationOptionAlert); // 需要执行这个方法，选择是否提醒用户，有 Badge、Sound、Alert 三种类型可以选择设置
}

// iOS 10 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)(void))completionHandler  API_AVAILABLE(ios(10.0)){
    // Required
    NSDictionary * userInfo = response.notification.request.content.userInfo;
    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
    }
    completionHandler();  // 系统要求执行这个方法
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    
    // Required, iOS 7 Support
    [JPUSHService handleRemoteNotification:userInfo];
    completionHandler(UIBackgroundFetchResultNewData);
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    [JPUSHService handleRemoteNotification:userInfo];
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    [self setBadgeWillEnterForeground:application];
    
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    [self setBadgeWillEnterForeground:application];
     [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
}

- (void )setBadgeWillEnterForeground:(UIApplication *)application{
    [JPUSHService setBadge:0];
    [application setApplicationIconBadgeNumber:0];
    [application cancelAllLocalNotifications];
}


@end
